//
//  ZXchanceToOrderController.m
//  qianke
//
//  Created by ZX on 2017/7/10.
//  Copyright © 2017年 ZX. All rights reserved.
//

#import "ZXchanceToOrderController.h"
#import "ZXToOrderCell.h"
#import "ZXToOrderModel.h"
#import "ZXsaleactivity2Cell.h"

#import "AddSaleActivityViewController.h"
#import "ZXSaleActivityController.h"

@interface ZXchanceToOrderController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
/*ilstArr*/
@property(copy ,nonatomic)NSMutableArray*listArr;
@property(copy ,nonatomic)NSMutableArray*thisMouthArr;
@property(copy ,nonatomic)NSMutableArray*tlastMouthArr;

@property(assign ,nonatomic)BOOL isRefersh;
@property(assign ,nonatomic)int pageNo;
@property(copy ,nonatomic)NSString * Count;
@property(assign ,nonatomic)int pageSize;
@property(assign ,nonatomic)int upLoadNumber;
@property (weak, nonatomic) IBOutlet UIButton *leftBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightConstraint;
@property (weak, nonatomic) IBOutlet UIButton *rightBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftConstraint;
@property (weak, nonatomic) IBOutlet UIView *btnBigView;
@property (weak, nonatomic) IBOutlet UIView *emptyView;
@end

@implementation ZXchanceToOrderController

@synthesize myTableView;

- (void)viewDidLoad {
    [super viewDidLoad];
    _isRefersh = NO;
    _pageSize = 10;
    _pageNo = 2;
    _rightConstraint.constant = ZXtableViewMargin;
    _leftConstraint.constant = ZXtableViewMargin;
    NSLogfun;
    self.view.backgroundColor = baseBackgroundColor;
    if (_type) {
        [_leftBtn setBackgroundColor:baseBlueColor];
        [_leftBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_rightBtn setBackgroundColor:[UIColor whiteColor]];
        [_rightBtn setTitleColor:baseBlueColor forState:UIControlStateNormal];
    }else{
        [_rightBtn setBackgroundColor:baseBlueColor];
        [_rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_leftBtn setBackgroundColor:[UIColor whiteColor]];
        [_leftBtn setTitleColor:baseBlueColor forState:UIControlStateNormal];
        
    }
    if (!_listArr) {
        _listArr =[[NSMutableArray alloc]init];
    }
    if (!_thisMouthArr) {
        _listArr =[[NSMutableArray alloc]init];
    }if (!_tlastMouthArr) {
        _listArr =[[NSMutableArray alloc]init];
    }
    if (_type) {
        [self thisMounthData];
    }else [self lastMounthData];
    [self loadData];
    [self creatTableView];
    myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"刷新");
        _isRefersh = YES;
        my_AppDelegate.isShow = YES;
        if (_type) {
            [self thisMounthData];
        }else [self lastMounthData];
    }];
    myTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    [self layout];
}
-(void)viewWillDisappear:(BOOL)animated{
    my_AppDelegate.isShow = NO;
}
-(void)layout{
    UIBezierPath *maskPath=[UIBezierPath bezierPathWithRoundedRect:_rightBtn.bounds byRoundingCorners:UIRectCornerTopRight|UIRectCornerBottomRight cornerRadii:CGSizeMake(5, 5)];
    CAShapeLayer *maskLayer=[[CAShapeLayer alloc]init];
    maskLayer.frame=_rightBtn.bounds;
    maskLayer.path=maskPath.CGPath;
    _rightBtn.layer.mask=maskLayer;
    _btnBigView.layer.borderWidth = 1;
    _btnBigView.layer.borderColor = baseBlueColor.CGColor;
    _btnBigView.layer.cornerRadius = 5;
    
    UIBezierPath *maskPath2=[UIBezierPath bezierPathWithRoundedRect:_leftBtn.bounds byRoundingCorners:UIRectCornerTopLeft|UIRectCornerBottomLeft cornerRadii:CGSizeMake(5, 5)];
    CAShapeLayer *maskLayer2=[[CAShapeLayer alloc]init];
    maskLayer2.frame=_leftBtn.bounds;
    maskLayer2.path=maskPath2.CGPath;
    _leftBtn.layer.mask=maskLayer2;
    
}

-(void)thisMounthData{
    _type = YES;
    _emptyView.hidden = YES;
    NSString * beginTim = [ZXToolObj getMonthBeginWith:[NSString stringWithFormat:@"2017-%@",[ZXToolObj getMonth]]];
    NSString * endTim = [ZXToolObj getMonthEndWith:[NSString stringWithFormat:@"2017-%@",[ZXToolObj getMonth]]];
    _beginTim = [NSString stringWithFormat:@"%@",beginTim];
    _endTim = [NSString stringWithFormat:@"%@",endTim];
    if (!_isRefersh) {
        if (_thisMouthArr.count==0) {
            [self loadData];
        }else{
            [_listArr removeAllObjects];
            _listArr = [_thisMouthArr mutableCopy];
            [self.myTableView reloadData];
        }
    }else{
        [self loadData];
    }

}
-(void)lastMounthData{
    _type = NO;
    _emptyView.hidden = YES;
    NSString * beginTim = [ZXToolObj getMonthBeginWith:[NSString stringWithFormat:@"2017-%@",[ZXToolObj getLastMonth]]];
    NSString * endTim = [ZXToolObj getMonthEndWith:[NSString stringWithFormat:@"2017-%@",[ZXToolObj getLastMonth]]];
    _beginTim = [NSString stringWithFormat:@"%@ 00:00:00",beginTim];
    _endTim = [NSString stringWithFormat:@"%@ 23:59:59",endTim];
    if (!_isRefersh) {
        if (_tlastMouthArr.count==0) {
            [self loadData];
        }else{
            [_listArr removeAllObjects];
            _listArr = [_tlastMouthArr mutableCopy];
            [self.myTableView reloadData];
        }
    }else{
        [self loadData];
    }
}
-(void)loadData{
    myTableView.mj_footer.hidden = NO;
    _emptyView.hidden = NO;
    NSString *strURL = [NSString stringWithFormat:@"%@scrmForApp/guestOrder/1/10?userName=%@&uid=%@&startTime=%@&endTime=%@",ZXBaseURL,my_AppDelegate.userName,my_AppDelegate.uid, _beginTim,_endTim];
    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:strURL];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    [mutableRequest addValue:my_AppDelegate.access_token forHTTPHeaderField:accessTokenKey];
    request = [mutableRequest copy];
    [_listArr removeAllObjects];
    [myTableView reloadData];
    [HTTPHelper GetHeadmutableRequest:request success:^(NSDictionary *data) {
        NSLog(@"%@",data);
        NSLog(@"message===%@",[data objectForKey:@"message"]);
        NSArray * arr = [data objectForKey:@"data"];
        NSString * temStr =[data objectForKey:@"msgCod"];
        if ([temStr isEqualToString:@"50000"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                myTableView.mj_footer.hidden = YES;
            });
        }
        _Count = [data objectForKey:@"count"];
        [_listArr removeAllObjects];
        if (![arr isEqual:[NSNull null]]&&arr){
            for (NSDictionary * dic in arr) {
                ZXToOrderModel * model = [ZXToOrderModel new];
                if (dic&&![dic isEqual:[NSNull null]]){
                    [model setValuesForKeysWithDictionary:dic];
                }
                [_listArr addObject:model];
            }
            if (arr&&![arr isEqual:[NSNull null]]) {
                if (arr.count<10) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        myTableView.mj_footer.hidden = YES;
                    });
                }
            }
            NSLog(@"listArr==%@",_listArr);
            NSLog(@"listArr==%lu",(unsigned long)_listArr.count);
            if (_type) {
                _thisMouthArr =[_listArr mutableCopy];
            }else {
                _tlastMouthArr = [_listArr mutableCopy];
            }
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                myTableView.mj_footer.hidden = YES;
            });
        }
            dispatch_async(dispatch_get_main_queue(), ^{
                [myTableView reloadData];
                if (_listArr.count>0) {
                    _emptyView.hidden = YES;
                }else{
                    _emptyView.hidden = NO;
                }
                [myTableView.mj_header endRefreshing];
            });
    } failure:^(NSError *error) {
        [myTableView.mj_header endRefreshing];
    }];
    
}
-(void)loadMoreData{
    my_AppDelegate.isShow = YES;
    if (_Count.intValue%_pageSize) {
        _upLoadNumber = _Count.intValue/_pageSize + 1;
    }else _upLoadNumber = _Count.intValue/_pageSize;
    
    NSString *strURL = [NSString stringWithFormat:@"%@scrmForApp/guestOrder/%d/%d?uid=%@&userName=%@&startTime=%@&endTime=%@",ZXBaseURL,_pageNo,_pageSize,my_AppDelegate.uid,my_AppDelegate.userName,_beginTim,_endTim];
    NSLog(@"strURL==%@",strURL);
    strURL = [strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:strURL];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    [mutableRequest addValue:my_AppDelegate.access_token forHTTPHeaderField:accessTokenKey];
    request = [mutableRequest copy];
    [HTTPHelper GetHeadmutableRequest:request success:^(NSDictionary *data) {
        NSLog(@"%@",data);
        NSLog(@"%@",[data objectForKey:@"message"]);
        NSString * string = [data objectForKey:@"message"];
        NSArray * arr = [data objectForKey:@"data"];
        NSString * msgCod = [data objectForKey:@"msgCod"];
        if ([string containsString:@"无数据" ]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [myTableView.mj_footer endRefreshing];
                [myTableView.mj_footer setState:MJRefreshStateNoMoreData];
                myTableView.mj_footer.hidden = YES;
            });
            return ;
        }
        if (![msgCod isEqualToString:@"S0001"]) {
            _pageNo++;
        }else{
            [myTableView.mj_footer setState:MJRefreshStateNoMoreData];
            myTableView.mj_footer.hidden = YES;
            return ;
        }
        
        if (![arr isEqual:[NSNull null]]&&arr){
            [_listArr removeAllObjects];
            for (NSDictionary * dic in arr) {
                ZXToOrderModel * model = [ZXToOrderModel new];
                if (dic&&![dic isEqual:[NSNull null]]){
                    [model setValuesForKeysWithDictionary:dic];
                }
                [_listArr addObject:model];
            }
            NSLog(@"listArr.count==%lu",(unsigned long)_listArr.count);
            
            if (_type) {
                for (ZXToOrderModel * model in _listArr) {
                    
                    [_thisMouthArr addObject:model];
                }
                _listArr =[_thisMouthArr mutableCopy];
            }else {
                for (ZXToOrderModel * model in _listArr) {
                    
                    [_tlastMouthArr addObject:model];
                }
                _listArr = [_tlastMouthArr mutableCopy];
            }
            NSLog(@"listArr.count==%lu",(unsigned long)_listArr.count);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [myTableView reloadData];
                [myTableView.mj_footer endRefreshing];
            });
        }
    } failure:^(NSError *error) {
        [myTableView.mj_footer endRefreshing];
    }];
}
#pragma mark --tableview datasouse
-(void)creatTableView{
    myTableView.backgroundColor = [UIColor clearColor];
    myTableView.separatorStyle = NO;
    [self.view addSubview:myTableView];
    [myTableView registerNib:[UINib nibWithNibName:NSStringFromClass([ZXToOrderCell class]) bundle:nil] forCellReuseIdentifier:@"cell"];
    myTableView.delegate = self;
    myTableView.dataSource = self;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_listArr.count>0) {
        return _listArr.count+1;
    }else{
        return _listArr.count;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == _listArr.count) {
        ZXsaleactivity2Cell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"ZXsaleactivity2Cell" owner:nil options:nil] firstObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.contentLabel.text = @"以上是最近订单记录";
        cell.backgroundColor = baseBackgroundColor;
        return cell;
    }

    ZXToOrderCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.ZXToOrderModel1 = _listArr[indexPath.row];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == _listArr.count) {
        return 33;
    }
    ZXToOrderModel * model = _listArr[indexPath.row];
    int height1 = [model.address stringSizeWithMaxSize:CGSizeMake(ScreenWidth*2/3, ScreenHeight) withFont:textfont].height;
    return 170+height1;
}

#pragma mark -- tableview delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    ZXSaleActivityController * saleVc = [ZXSaleActivityController new];
//    myTableViewCell * cell =[tableView cellForRowAtIndexPath:indexPath];
//    saleVc.chanceId = cell.chanceId;
//    saleVc.title = @"销售活动";
//    saleVc.type = YES;
//    saleVc.view.backgroundColor = baseBackgroundColor;
//    [self.navigationController pushViewController:saleVc animated:YES];
}
- (IBAction)leftBtnClick:(id)sender {
     [SVProgressHUD dismiss];
    _leftBtn.backgroundColor = baseBlueColor;
    _rightBtn.backgroundColor = [UIColor whiteColor];
    [_leftBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_rightBtn setTitleColor:baseBlueColor forState:UIControlStateNormal];
    _type = YES;
    _isRefersh = NO;
    [self thisMounthData];
}
- (IBAction)rightBtnClick:(id)sender {
     [SVProgressHUD dismiss];
    _rightBtn.backgroundColor = baseBlueColor;
    _leftBtn.backgroundColor = [UIColor whiteColor];
    [_rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_leftBtn setTitleColor:baseBlueColor forState:UIControlStateNormal];
    _type = NO;
    _isRefersh = NO;
    [self lastMounthData];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
